package com.example.demo.redis;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OperateServiceImpl implements OperateService{

    @Resource(name = "defaultRedisson")
    private RedissonClient redissonClient;

    /**
     * 获取Map对象
     *
     * @param mapName
     * @return
     */
    @Override
    public <K, V> Map<K, V> getMap(String mapName) {
        RMap<K, V> map = redissonClient.getMap(mapName);
        return map;
    }

    @Override
    public void putMapValue(String mapName, Object key, Object value, Long timeToLive, TimeUnit timeUnit) {
        RMap<Object, Object> map = redissonClient.getMap(mapName);
        map.put(key, value);
        if(null != timeToLive && timeToLive.longValue() > 0l && null != timeUnit) {
            map.expire(timeToLive, timeUnit);
        }
    }

    @Override
    public Object getMapValue(String mapName, Object key) {
        RMap<Object, Object> map = redissonClient.getMap(mapName);
        return map.get(key);
    }

    @Override
    public void removeMapKey(String mapName, Object key) {
        redissonClient.getMap(mapName).remove(key);
    }


}
